package com.hb.trans.mvp.ui.activity


import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import androidx.core.content.ContextCompat
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.basiclib.base.BaseActivity
import com.basiclib.utils.ImmersionBar
import com.basiclib.utils.VerifyUtils
import com.basiclib.utils.hideSoftKeyword
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.ctcnit.templatepro.global.MyGlideModule
import com.hb.trans.R
import com.hb.trans.global.ACTIVITY_TRANS_CHECK_LOGIN
import com.hb.trans.global.ACTIVITY_TRANS_INFO
import com.hb.trans.mvp.contract.TransCheckLoginContract
import com.hb.trans.mvp.presenter.TransCheckLoginPresenter
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.textChanges
import dagger.android.AndroidInjection
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_trans_check_login.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject


@Route(path = ACTIVITY_TRANS_CHECK_LOGIN)
class TransCheckLoginActivity : BaseActivity(), TransCheckLoginContract.View, OnOptionsSelectListener {

    @Inject
    lateinit var mPresenter: TransCheckLoginPresenter

    var pvOptions: OptionsPickerView<String>? = null
    val carTypes: List<String> by lazy { resources.getStringArray(R.array.car_type).toList() }

    override fun getContentViewResId(): Int = R.layout.activity_trans_check_login

    override fun onActivityInject() {
        AndroidInjection.inject(this)
    }

    override fun attachView(savedInstanceState: Bundle?) {
        mPresenter.attachView(this)
        ImmersionBar.with(this)
            .statusBarColor(R.color.colorPrimary)
            .init()
    }

    override fun getPresenter(): TransCheckLoginPresenter = mPresenter

    override fun initView() {

    }

    override fun initData() {

    }

    @SuppressLint("CheckResult")
    override fun setListener() {
        transToolbar.backClick()?.subscribe {
            hideSoftKeyword()
            finish()
        }

        rlContainer.clicks().subscribe {
            hideSoftKeyword()
        }
        Observable.mergeArray(etPhoneNumber.clicks(), etSecurityCode.clicks(), etCardNumber.clicks())
            .subscribe {
                dismissPickerView()
            }
        Observable.mergeArray(
            etPhoneNumber.textChanges(),
            etCardNumber.textChanges(),
            etCarType.textChanges(),
            etSecurityCode.textChanges()
        ).debounce(500, TimeUnit.MILLISECONDS)
            .map {
                val phoneNumber = etPhoneNumber.text?.toString()?.trim()
                val cardCode = etCardNumber.text?.toString()?.trim()
                val carType = etCarType.text?.toString()?.trim()
                val securityCode = etSecurityCode.text?.toString()?.trim()
                phoneNumber.isNullOrBlank() || cardCode.isNullOrBlank() || carType.isNullOrBlank() || securityCode.isNullOrBlank()
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                btnLogin.isEnabled = !it
            }

        btnLogin.clicks().subscribe {
            dismissPickerView()
            val phoneNumber = etPhoneNumber.text?.toString()?.trim()
            val cardCode = etCardNumber.text?.toString()?.trim()
            val cardCodeResult = VerifyUtils.iDCardValidate(cardCode)
            val carType = etCarType.text?.toString()?.trim()
            val securityCode = etSecurityCode.text?.toString()?.trim()
            when {
                phoneNumber.isNullOrBlank() -> showShortToast("手机号不能为空")
                VerifyUtils.checkPhone(phoneNumber) -> showShortToast("手机号码不正确")
                !cardCodeResult.first -> showShortToast(cardCodeResult.second)
                carType.isNullOrBlank() -> showShortToast("请选择培训车型")
                securityCode.isNullOrBlank() -> showShortToast("验证码不能为空")
                else -> {
                    mPresenter.login(phoneNumber, cardCode!!, carType, securityCode)
                }
            }
        }
        llType.clicks().subscribe {
            hideSoftKeyword()
            showPickView()
        }

        ibSecurity.clicks()
            .subscribe {
                mPresenter.loadSecurity()
            }
    }

    private fun showPickView() {
        pvOptions = OptionsPickerBuilder(this, this)
            .setSelectOptions(0)//设置默认选中项
            .setSubmitText("确定")//确定按钮文字
            .setCancelText("取消")//取消按钮文字
            .setSubCalSize(18)//确定和取消文字大小
            .setTitleSize(20)//标题文字大小
            .setSubmitColor(ContextCompat.getColor(this, R.color.colorPrimaryDark))//确定按钮文字颜色
            .setCancelColor(ContextCompat.getColor(this, R.color.colorPrimaryDark))//取消按钮文字颜色
            .setTitleBgColor(ContextCompat.getColor(this, R.color.white))//标题背景颜色 Night mode
            .setBgColor(ContextCompat.getColor(this, R.color.white))//滚轮背景颜色 Night mode
            .setContentTextSize(18)//滚轮文字大小
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setCyclic(false, false, false)//循环与否
            .setOutSideCancelable(false)//点击外部dismiss default true
            .isDialog(false)//是否显示为对话框样式
            .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
            .build<String>()

        pvOptions!!.setPicker(carTypes, null, null)//添加数据源
        pvOptions!!.show(true)
    }

    override fun onOptionsSelect(options1: Int, options2: Int, options3: Int, v: View?) {
        etCarType.text = carTypes[options1]
    }

    private fun dismissPickerView() {
        if (pvOptions != null && pvOptions!!.isShowing) {
            pvOptions?.dismiss()
        }
    }

    override fun loginSucess() {
        ARouter.getInstance().build(ACTIVITY_TRANS_INFO).navigation()
    }

    override fun setSecurityImage(bitmap: Bitmap) {
        MyGlideModule.load(this, bitmap, ibSecurity)
    }

    override fun finishSelf() {
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        ImmersionBar.with(this).destroy()
    }
}
